<template>
	<view class="container">
		<!-- 搜索栏 -->
		<view class="search-bar">
			<uni-search-bar 
				v-model="searchValue" 
				placeholder="搜索优惠团购" 
				@confirm="handleSearch"
				@clear="handleClear"
			></uni-search-bar>
		</view>
		
		<!-- 团购列表 -->
		<view class="group-list" v-if="youhuiList.length > 0">
			<view class="info" v-for="item in youhuiList" :key="item.id" @click="handleCardClick(item)">
				<view class="img">
					<image :src="item.img || item.url || '/static/tuangou-youhui/优惠卷.png'" mode="aspectFill"></image>
					<view class="discount-tag" v-if="item.originalPrice && item.presentPrice">
						<text>{{ calculateDiscount(item.originalPrice, item.presentPrice) }}折</text>
					</view>
				</view>
				<view class="bottom-info">
					<view class="left">
						<span class="title-text">{{ item.title }}</span>
						<view class="price-info" v-if="item.presentPrice">
							<text class="present-price">￥{{ item.presentPrice }}</text>
							<text class="original-price" v-if="item.originalPrice">￥{{ item.originalPrice }}</text>
						</view>
						<view class="stats-info">
							<text class="read-count">阅读量：{{ item.num || 0 }}</text>
							<text class="participants">参与人数：{{ item.participants || 0 }}</text>
						</view>
						<view class="time-info" v-if="item.endTime">
							<text>截止：{{ formatDate(item.endTime) }}</text>
						</view>
					</view>
					<view class="right">
						<span>详情
							<image src="/static/tuangou-youhui/收起箭头小.png" mode=""></image>
						</span>
					</view>
				</view>
			</view>
		</view>
		
		<!-- 空状态 -->
		<view class="empty-state" v-else-if="!loading">
			<image src="/static/tuangou-youhui/优惠卷.png" mode="aspectFit"></image>
			<text>暂无优惠团购信息</text>
		</view>
		
		<!-- 加载状态 -->
		<view class="loading-state" v-if="loading">
			<uni-load-more status="loading"></uni-load-more>
		</view>
	</view>
</template>

<script>
	export default {
		data() {
			return {
				searchValue: '',
				youhuiList: [],
				loading: false,
				pageNum: 1,
				pageSize: 10,
				hasMore: true,
				// API基础地址 - 直接访问后端服务
				baseUrl: 'http://localhost:9201',
				// 是否启用真实API（设为false时直接使用模拟数据）
				// 要启用真实API，需要：
				// 1. 确保后端服务正在运行
				// 2. 配置正确的baseUrl
				// 3. 确保接口不需要权限或已配置白名单
				// 4. 将此值设为true
				useRealApi: true
			}
		},
		onLoad() {
			this.loadGroupBuyingList();
		},
		onShow() {
			// 页面显示时刷新数据（从详情页返回时）
			this.refresh();
		},
		onReachBottom() {
			if (this.hasMore && !this.loading) {
				this.loadMore();
			}
		},
		onPullDownRefresh() {
			this.refresh();
		},
		methods: {
			// 加载团购列表
			async loadGroupBuyingList() {
				this.loading = true;
				try {
					// 如果禁用真实API，直接使用模拟数据
					if (!this.useRealApi) {
						console.log('使用模拟数据模式');
						const mockData = this.getMockData();
						
						if (this.pageNum === 1) {
							this.youhuiList = mockData;
						} else {
							this.youhuiList = [...this.youhuiList, ...mockData];
						}
						
						this.hasMore = mockData.length === this.pageSize;
						return;
					}
					
					// 调用API接口
					const response = await this.getGroupBuyingListApi({
						pageNum: this.pageNum,
						pageSize: this.pageSize,
						title: this.searchValue
					});
					
					// 调试信息：打印API返回的数据结构
					console.log('API返回的数据结构:', response);
					
					// 处理API返回的数据结构
					let dataList = [];
					
					// 检查是否有错误码
					if (response && response.code && response.code !== 200) {
						console.log('API返回错误:', response.msg);
						throw new Error(response.msg || 'API调用失败');
					}
					
					if (response && response.rows) {
						dataList = response.rows;
						console.log('使用 response.rows:', dataList);
					} else if (response && Array.isArray(response)) {
						dataList = response;
						console.log('使用 response 数组:', dataList);
					} else if (response && response.data) {
						dataList = response.data;
						console.log('使用 response.data:', dataList);
					} else {
						console.log('API返回数据格式不符合预期，使用模拟数据');
						throw new Error('API返回数据格式错误');
					}
					
					// 过滤已过期的团购
					const validData = dataList.filter(item => !this.isExpired(item.endTime));
					
					if (this.pageNum === 1) {
						this.youhuiList = validData;
					} else {
						this.youhuiList = [...this.youhuiList, ...validData];
					}
					
					this.hasMore = validData.length === this.pageSize;
				} catch (error) {
					console.error('加载团购列表失败:', error);
					// 如果API调用失败，使用模拟数据
					const mockData = this.getMockData();
					
					if (this.pageNum === 1) {
						this.youhuiList = mockData;
					} else {
						this.youhuiList = [...this.youhuiList, ...mockData];
					}
					
					this.hasMore = mockData.length === this.pageSize;
					
					// 只在第一次加载时显示提示
					if (this.pageNum === 1) {
						let errorMsg = '网络异常，显示模拟数据';
						if (error.message.includes('未授权')) {
							errorMsg = '需要登录才能查看团购信息，显示模拟数据';
						} else if (error.message.includes('权限不足')) {
							errorMsg = '权限不足，显示模拟数据';
						} else if (error.message.includes('接口不存在')) {
							errorMsg = '接口暂未开放，显示模拟数据';
						}
						
						uni.showToast({
							title: errorMsg,
							icon: 'none',
							duration: 3000
						});
					}
				} finally {
					this.loading = false;
					uni.stopPullDownRefresh();
				}
			},
			
			// API调用方法
			getGroupBuyingListApi(params) {
				return new Promise((resolve, reject) => {
					// 获取token
					const token = uni.getStorageSync('token') || uni.getStorageSync('access_token');
					
					uni.request({
						url: `${this.baseUrl}/system/buying/public/list`,
						method: 'GET',
						data: {
							pageNum: params.pageNum || 1,
							pageSize: params.pageSize || 10,
							title: params.title || '',
							deleted: 0 // 只查询未删除的数据
						},
						header: {
							'Content-Type': 'application/json',
							'Authorization': token ? `Bearer ${token}` : ''
						},
						success: (res) => {
							console.log('API响应状态:', res.statusCode);
							console.log('API响应数据:', res.data);
							
							if (res.statusCode === 200) {
								resolve(res.data);
							} else if (res.statusCode === 401) {
								reject(new Error('未授权，请先登录'));
							} else if (res.statusCode === 403) {
								reject(new Error('权限不足'));
							} else if (res.statusCode === 404) {
								reject(new Error('接口不存在'));
							} else {
								reject(new Error(`请求失败: ${res.statusCode} - ${res.data?.msg || '未知错误'}`));
							}
						},
						fail: (err) => {
							console.error('网络请求失败:', err);
							reject(err);
						}
					});
				});
			},
			
			// 模拟数据
			getMockData() {
				const mockList = [
					{
						id: 1,
						title: "汽车惠民活动走进社区，购车享受最高2万元补贴",
						publisher: "济源汽车行业",
						publishTime: "2024-01-15",
						img: "/static/tuangou-youhui/优惠卷.png",
						url: "/static/tuangou-youhui/优惠卷.png",
						content: "汽车惠民活动走进社区，购车享受最高2万元补贴，限时优惠，机会难得！",
						originalPrice: 200000,
						presentPrice: 180000,
						endTime: "2024-12-31",
						telephone: "0391-1234567",
						note: "本活动仅限新用户，每人限购一次",
						num: 1250,
						deleted: 0
					},
					{
						id: 2,
						title: "清凉一夏购车节，新能源汽车限时优惠",
						publisher: "新能源推广中心",
						publishTime: "2024-01-10",
						img: "/static/tuangou-youhui/清凉一夏.png",
						url: "/static/tuangou-youhui/清凉一夏.png",
						content: "清凉一夏购车节，新能源汽车限时优惠，环保出行，绿色生活！",
						originalPrice: 150000,
						presentPrice: 120000,
						endTime: "2024-08-31",
						telephone: "0391-7654321",
						note: "活动期间购车送充电桩",
						num: 890,
						deleted: 0
					}
				];
				
				// 根据页码返回数据
				const start = (this.pageNum - 1) * this.pageSize;
				const end = start + this.pageSize;
				return mockList.slice(start, end);
			},
			
			// 搜索
			handleSearch() {
				this.pageNum = 1;
				this.hasMore = true;
				this.loadGroupBuyingList();
			},
			
			// 清空搜索
			handleClear() {
				this.searchValue = '';
				this.handleSearch();
			},
			
			// 加载更多
			loadMore() {
				this.pageNum++;
				this.loadGroupBuyingList();
			},
			
			// 刷新
			refresh() {
				this.pageNum = 1;
				this.hasMore = true;
				this.loadGroupBuyingList();
			},
			
			// 点击优惠信息卡片
			handleCardClick(item) {
			    // 直接跳转到详情页面
			    uni.navigateTo({
			        url: `/index-item/GroupDeal/DiscountInfo?id=${item.id}`
			    });
			},
			
			// 格式化日期
			formatDate(dateStr) {
				if (!dateStr) return '';
				const date = new Date(dateStr);
				const year = date.getFullYear();
				const month = String(date.getMonth() + 1).padStart(2, '0');
				const day = String(date.getDate()).padStart(2, '0');
				return `${year}-${month}-${day}`;
			},
			
			// 计算折扣百分比
			calculateDiscount(originalPrice, presentPrice) {
				if (!originalPrice || !presentPrice || originalPrice <= 0) return 0;
				return Math.round((1 - presentPrice / originalPrice) * 100);
			},
			
			// 检查团购是否已过期
			isExpired(endTime) {
				if (!endTime) return true;
				return new Date(endTime) < new Date();
			}
		}
	}
</script>

<style>
	.container {
		background: linear-gradient(to bottom, #3284fc 350rpx, #f5f5f5 350rpx);
		min-height: 100vh;
		padding: 10rpx 20rpx;
		box-sizing: border-box;
	}
	
	.search-bar {
		margin-top: 20rpx;
		margin-bottom: 20rpx;
	}
	
	.group-list {
		margin-top: 20rpx;
	}

	.info {
		margin-top: 30rpx;
		background: #fff;
		border-radius: 30rpx;
		padding: 20rpx;
		min-height: 450rpx;
		box-sizing: border-box;
		position: relative;
		box-shadow: 0 4rpx 20rpx rgba(0, 0, 0, 0.08);
		display: flex;
		flex-direction: column;
	}

	.img {
		box-sizing: border-box;
		width: 100%;
		height: 280rpx;
		position: relative;
		flex-shrink: 0;
	}

	.img image {
		border-radius: 30rpx;
		width: 100%;
		height: 100%;
	}
	
	.discount-tag {
		position: absolute;
		top: 10rpx;
		right: 10rpx;
		background: #ff4757;
		color: #fff;
		padding: 4rpx 8rpx;
		border-radius: 8rpx;
		font-size: 20rpx;
	}

	.bottom-info {
		box-sizing: border-box;
		width: 100%;
		display: flex;
		justify-content: space-between;
		align-items: flex-start;
		margin-top: 15rpx;
		padding: 10rpx;
		min-height: 100rpx;
		flex: 1;
	}

	.bottom-info .left {
		font-size: 28rpx;
		font-weight: 400;
		margin-right: 20rpx;
		width: 70%;
		display: flex;
		flex-direction: column;
		gap: 8rpx;
		flex: 1;
	}
	
	.title-text {
		display: block;
		white-space: nowrap;
		overflow: hidden;
		text-overflow: ellipsis;
		max-width: 100%;
		font-weight: 600;
		color: #333;
		font-size: 26rpx;
		line-height: 1.3;
		flex-shrink: 0;
	}
	
	.price-info {
		display: flex;
		align-items: center;
		gap: 10rpx;
		flex-shrink: 0;
	}
	
	.present-price {
		font-size: 24rpx;
		font-weight: 600;
		color: #ff4757;
	}
	
	.original-price {
		font-size: 20rpx;
		color: #999;
		text-decoration: line-through;
	}
	
	.stats-info {
		display: flex;
		align-items: center;
		gap: 20rpx;
		font-size: 20rpx;
		color: #666;
		flex-shrink: 0;
	}
	
	.read-count {
		color: #3284fc;
	}
	
	.participants {
		color: #ff6b35;
	}
	
	.time-info {
		font-size: 20rpx;
		color: #666;
		line-height: 1.2;
		white-space: nowrap;
		overflow: hidden;
		text-overflow: ellipsis;
		flex-shrink: 0;
	}
	
	.bottom-info .right {
		text-align: right;
		display: flex;
		align-items: center;
		justify-content: flex-end;
		flex-shrink: 0;
	}

	.bottom-info .right span {
		color: gray;
		display: flex;
		align-items: center;
		font-size: 24rpx;
	}

	.bottom-info .right image {
		width: 15rpx;
		height: 20rpx;
		margin-left: 10rpx;
	}
	
	.empty-state {
		display: flex;
		flex-direction: column;
		align-items: center;
		justify-content: center;
		padding: 100rpx 0;
	}
	
	.empty-state image {
		width: 200rpx;
		height: 200rpx;
		margin-bottom: 20rpx;
		opacity: 0.5;
	}
	
	.empty-state text {
		font-size: 28rpx;
		color: #999;
	}
	
	.loading-state {
		display: flex;
		justify-content: center;
		padding: 20rpx 0;
	}
</style>